package apple

import (
  "github.com/smartwalle/apple"
  "os"
  "pay/config"
)

type ApplePay struct {
  conf   *config.ApplePayConf
  client *apple.Client
}

func NewApplePay(conf *config.ApplePayConf) (*ApplePay, error) {

  if !conf.Enable {
    return &ApplePay{conf: conf}, nil
  }

  keyBytes, err := os.ReadFile(conf.PrivateKeyPath)
  if err != nil {
    return nil, err
  }

  client, err := apple.New(keyBytes, conf.PrivateKeyID, conf.IssuerId, conf.BundleId, !conf.Debug)
  return &ApplePay{
    conf:   conf,
    client: client,
  }, nil
}

func (p *ApplePay) ValidateBundleId(bundleId string) bool {
  return p.conf.BundleId == bundleId
}

func (p *ApplePay) GetTransaction(transactionId string) (*apple.TransactionResponse, error) {
  transaction, err := p.client.GetTransaction(transactionId)
  if err != nil {
    return nil, err
  }
  return transaction, err
}
